/**
 * 音频播放器工具类
 * 提供音频播放、暂停、停止等功能
 */

export interface AudioPlayerOptions {
  volume?: number;          // 音量 (0-1)
  loop?: boolean;          // 是否循环播放
  preload?: 'auto' | 'metadata' | 'none'; // 预加载策略
  crossOrigin?: string;    // 跨域设置
}

export interface AudioPlayerEvents {
  onLoadStart?: () => void;
  onCanPlay?: () => void;
  onPlay?: () => void;
  onPause?: () => void;
  onEnded?: () => void;
  onError?: (error: Event) => void;
  onTimeUpdate?: (currentTime: number, duration: number) => void;
  onProgress?: (loaded: number, total: number) => void;
}

export class AudioPlayer {
  private audio: HTMLAudioElement | null = null;
  private options: AudioPlayerOptions;
  private events: AudioPlayerEvents;
  private _isPlaying: boolean = false;
  private _isLoading: boolean = false;

  constructor(options: AudioPlayerOptions = {}, events: AudioPlayerEvents = {}) {
    this.options = {
      volume: 1,
      loop: false,
      preload: 'metadata',
      ...options
    };
    this.events = events;
  }

  /**
   * 加载音频文件
   */
  async load(url: string): Promise<void> {
    try {
      this._isLoading = true;
      
      // 清理之前的音频
      this.destroy();
      
      // 创建新的音频实例
      this.audio = new Audio(url);
      
      // 设置音频属性
      this.audio.volume = this.options.volume || 1;
      this.audio.loop = this.options.loop || false;
      this.audio.preload = this.options.preload || 'metadata';
      
      if (this.options.crossOrigin) {
        this.audio.crossOrigin = this.options.crossOrigin;
      }
      
      // 绑定事件监听器
      this.bindEvents();
      
      console.log('🎵 音频加载中:', url);
      
    } catch (error) {
      this._isLoading = false;
      console.error('❌ 音频加载失败:', error);
      throw error;
    }
  }

  /**
   * 播放音频
   */
  async play(): Promise<void> {
    if (!this.audio) {
      throw new Error('音频未加载');
    }

    try {
      await this.audio.play();
      this._isPlaying = true;
      console.log('▶️ 音频开始播放');
    } catch (error) {
      this._isPlaying = false;
      console.error('❌ 音频播放失败:', error);
      throw error;
    }
  }

  /**
   * 暂停音频
   */
  pause(): void {
    if (this.audio && !this.audio.paused) {
      this.audio.pause();
      this._isPlaying = false;
      console.log('⏸️ 音频暂停');
    }
  }

  /**
   * 停止音频
   */
  stop(): void {
    if (this.audio) {
      this.audio.pause();
      this.audio.currentTime = 0;
      this._isPlaying = false;
      console.log('⏹️ 音频停止');
    }
  }

  /**
   * 设置音量
   */
  setVolume(volume: number): void {
    if (this.audio) {
      this.audio.volume = Math.max(0, Math.min(1, volume));
    }
  }

  /**
   * 设置播放位置
   */
  setCurrentTime(time: number): void {
    if (this.audio) {
      this.audio.currentTime = time;
    }
  }

  /**
   * 获取当前播放时间
   */
  getCurrentTime(): number {
    return this.audio?.currentTime || 0;
  }

  /**
   * 获取音频总时长
   */
  getDuration(): number {
    return this.audio?.duration || 0;
  }

  /**
   * 获取播放状态
   */
  get isPlaying(): boolean {
    return this._isPlaying;
  }

  /**
   * 获取加载状态
   */
  get isLoading(): boolean {
    return this._isLoading;
  }

  /**
   * 获取音频是否已加载
   */
  get isLoaded(): boolean {
    return this.audio !== null;
  }

  /**
   * 绑定音频事件
   */
  private bindEvents(): void {
    if (!this.audio) return;

    this.audio.addEventListener('loadstart', () => {
      console.log('🔄 音频开始加载');
      this.events.onLoadStart?.();
    });

    this.audio.addEventListener('canplay', () => {
      this._isLoading = false;
      console.log('✅ 音频可以播放');
      this.events.onCanPlay?.();
    });

    this.audio.addEventListener('play', () => {
      this._isPlaying = true;
      console.log('▶️ 音频播放事件');
      this.events.onPlay?.();
    });

    this.audio.addEventListener('pause', () => {
      this._isPlaying = false;
      console.log('⏸️ 音频暂停事件');
      this.events.onPause?.();
    });

    this.audio.addEventListener('ended', () => {
      this._isPlaying = false;
      console.log('🏁 音频播放结束');
      this.events.onEnded?.();
    });

    this.audio.addEventListener('error', (error) => {
      this._isPlaying = false;
      this._isLoading = false;
      console.error('❌ 音频错误事件:', error);
      this.events.onError?.(error);
    });

    this.audio.addEventListener('timeupdate', () => {
      if (this.audio) {
        this.events.onTimeUpdate?.(this.audio.currentTime, this.audio.duration);
      }
    });

    this.audio.addEventListener('progress', () => {
      if (this.audio && this.audio.buffered.length > 0) {
        const loaded = this.audio.buffered.end(this.audio.buffered.length - 1);
        const total = this.audio.duration;
        this.events.onProgress?.(loaded, total);
      }
    });
  }

  /**
   * 销毁音频播放器
   */
  destroy(): void {
    if (this.audio) {
      this.audio.pause();
      this.audio.src = '';
      this.audio.load(); // 重置音频元素
      this.audio = null;
    }
    this._isPlaying = false;
    this._isLoading = false;
    console.log('🗑️ 音频播放器已销毁');
  }
}

/**
 * 创建音频播放器实例
 */
export function createAudioPlayer(options?: AudioPlayerOptions, events?: AudioPlayerEvents): AudioPlayer {
  return new AudioPlayer(options, events);
}

/**
 * 简单的音频播放函数
 */
export async function playAudio(url: string, options?: AudioPlayerOptions): Promise<AudioPlayer> {
  const player = createAudioPlayer(options);
  await player.load(url);
  await player.play();
  return player;
}

/**
 * 检查浏览器音频支持
 */
export function checkAudioSupport(): {
  canPlayMP3: boolean;
  canPlayWAV: boolean;
  canPlayOGG: boolean;
  canPlayAAC: boolean;
} {
  const audio = new Audio();
  
  return {
    canPlayMP3: audio.canPlayType('audio/mpeg') !== '',
    canPlayWAV: audio.canPlayType('audio/wav') !== '',
    canPlayOGG: audio.canPlayType('audio/ogg') !== '',
    canPlayAAC: audio.canPlayType('audio/aac') !== ''
  };
}

/**
 * 获取音频文件信息
 */
export function getAudioInfo(url: string): Promise<{
  duration: number;
  canPlay: boolean;
}> {
  return new Promise((resolve, reject) => {
    const audio = new Audio(url);
    
    audio.addEventListener('loadedmetadata', () => {
      resolve({
        duration: audio.duration,
        canPlay: true
      });
    });
    
    audio.addEventListener('error', () => {
      reject(new Error('无法加载音频文件'));
    });
    
    audio.load();
  });
}
